package com.fist.eth.flutter_plugin_eth_wallet.utils

import android.util.Log
import org.web3j.abi.TypeReference
import org.web3j.abi.datatypes.Address
import org.web3j.abi.datatypes.Function
import org.web3j.abi.datatypes.Type
import org.web3j.abi.datatypes.generated.Uint256
import org.web3j.crypto.Credentials
import org.web3j.protocol.Web3j
import org.web3j.protocol.core.RemoteCall
import org.web3j.protocol.core.methods.response.TransactionReceipt
import org.web3j.tx.Contract
import java.math.BigInteger

open class TokenContract protected constructor(contractAddress: String, web3j: Web3j, credentials: Credentials, gasPrice: BigInteger, gasLimit: BigInteger) : Contract(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit) {

    fun transfer(toAddress: String, value: BigInteger): RemoteCall<TransactionReceipt> {
        Log.i("transfer value", "$value")
        val function = Function(FUNC_TRANSFER, listOf<Type<*>>(Address(toAddress), Uint256(value)), emptyList())
        return executeRemoteCallTransaction(function)
    }

    fun balanceOf(address: String): RemoteCall<BigInteger> {
        val function = Function(FUNC_BALANCE_OF, listOf<Type<*>>(Address(address)), listOf<TypeReference<*>>(object : TypeReference<Uint256>() {}))
        return executeRemoteCallSingleValueReturn(function, BigInteger::class.java)
    }

    companion object {
        private const val BINARY = ""

        private const val FUNC_APPROVE = "approve"

        private const val FUNC_TOTALSUPPLY = "totalSupply"

        private const val FUNC_TRANSFER_FROM = "transferFrom"

        private const val FUNC_BALANCE_OF = "balanceOf"

        private const val FUNC_TRANSFER = "transfer"

        private const val FUNC_ALLOWANCE = "allowance"

        fun load(contractAddress: String, web3j: Web3j, credentials: Credentials, gasPrice: BigInteger, gasLimit: BigInteger): TokenContract {
            return TokenContract(contractAddress, web3j, credentials, gasPrice, gasLimit)
        }
    }
}

